<?php

class TicketQuery extends Doctrine_Query
{
  protected $is_visible_to_users_joined = false;
  protected $is_current_user_joined = false;
  protected $is_project_joined = false;


  /**
   * Instantiates UserQuery class
   *
   * @param Doctrine_Connection $conn
   * @param string $class
   * @return UserQuery
   */
  static public function create($conn = null, $class = null)
  {
    return parent::create($conn, 'TicketQuery')->from('Ticket t');
  }
  

  public function joinProject()
  {
    if (!$this->is_project_joined)
    {
      $this->leftJoin('t.Project p');
      $this->is_project_joined = true;
    }

    return $this;
  }

  public function joinVisibleToUsers()
  {
    if (!$this->is_visible_to_users_joined)
    {
      $this->leftJoin('t.VisibleToUsers vu')->leftJoin('vu.User vuu')->leftJoin('cu.Team vut');
      $this->is_visible_to_users_joined = true;
    }

    return $this;
  }


  public function joincurrentUser()
  {
    if (!$this->is_current_user_joined)
    {
      $this->leftJoin('t.CurrentUser cu')->leftJoin('cu.User cuu')->leftJoin('cu.Team cut');
      $this->is_current_user_joined = true;
    }

    return $this;
  }

  
  public function onlyVisible()
  {
    //Если текущий юзер может управлять любыми тикетами в своих проектах, то фильтр не накладывается
    if (sfContext::getInstance()->getUser()->hasCredential('manage_tickets_in_own_projects'))
      return $this;
      
    //Если текущий юзер может управлять любыми тикетами в любых проектах, то фильтр не накладывается
    if (sfContext::getInstance()->getUser()->hasCredential('manage_tickets_in_all_projects'))
      return $this;
      
    $user_id=sfContext::getInstance()->getUser()->getGuardUser()->id;
    $this->joinVisibleToUsers()->andWhere('vu.id = ?',$user_id);
    return $this;
  }
  
  public function filterById($id)
  {
    return $this->andWhere('t.id = ?',$id);
  }
  
  public function filterByProjectId($project_id)
  {
    return $this->andWhere('p.id = ?',$project_id);
  }
  
  
  
}
